package com.example.hospitalsystemclient.ui.doctorDetail;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.hospitalsystemclient.Dataclass.UrlData;
import com.example.hospitalsystemclient.MainActivity;
import com.example.hospitalsystemclient.R;
import com.example.hospitalsystemclient.ui.LoginActivity;
import com.example.hospitalsystemclient.ui.notifications.NotificationsFragment;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class DoctorDetailFragment extends Fragment {

    private TextView tvDocName, tvOfficeName, tvDocGender, tvDocAge, tvDocLevel, tvDocPrice, tvDocPhone;
    private ImageView ivDoctorImage;
    private final String[] date = {""};
    private final String[] time = {""};
    private UrlData urlData = new UrlData();
    private String[] times;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_doctor_detail, container, false);

        NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment_activity_main);

        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();

        NavigationUI.setupActionBarWithNavController((AppCompatActivity) requireActivity(), navController, appBarConfiguration);

        tvDocName = view.findViewById(R.id.tvDocName);
        tvOfficeName = view.findViewById(R.id.tvOfficeName);
        tvDocGender = view.findViewById(R.id.tvDocGender);
        tvDocAge = view.findViewById(R.id.tvDocAge);
        tvDocLevel = view.findViewById(R.id.tvDocLevel);
        tvDocPrice = view.findViewById(R.id.tvDocPrice);
        tvDocPhone = view.findViewById(R.id.tvDocPhone);
        ivDoctorImage = view.findViewById(R.id.ivDoctorImage);

        SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("DoctorPrefs", 0);

        Long docId = sharedPreferences.getLong("doc_id", -1);
        String docName = sharedPreferences.getString("doc_name", "");
        String officeName = sharedPreferences.getString("office_name", "");
        String docGender = sharedPreferences.getString("doc_gender", "");
        int docAge = sharedPreferences.getInt("doc_age", -1);
        String docLevel = sharedPreferences.getString("doc_level", "");
        int docPrice = sharedPreferences.getInt("doc_price", -1);
        String docPhone = sharedPreferences.getString("doc_phone", "");
        String imgAddr = sharedPreferences.getString("img_addr", "");

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();

        tvDocName.setText(docName);
        tvOfficeName.setText("科室："+ officeName);
        tvDocGender.setText("性别："+ docGender);
        tvDocAge.setText("年龄："+ String.valueOf(docAge)+"岁");
        tvDocLevel.setText("级别："+ docLevel);
        tvDocPrice.setText("挂号费："+ String.valueOf(docPrice)+".00元");
        tvDocPhone.setText("联系方式："+ docPhone);

        // 加载图片，假设使用 Picasso
        String imageUrl = "http://10yi2142777ik.vicp.fun:17590/file/img?img_addr=" + imgAddr;
        Picasso.get().load(imageUrl).into(ivDoctorImage);

        //预约日期选择

        Spinner dateSpinner = view.findViewById(R.id.date_spinner);
        String[] dates = getDatesForSpinner();

        // 创建 ArrayAdapter 使用默认的 spinner_item 布局
        ArrayAdapter<String> adapterDate = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, dates);
        // 设置下拉视图的布局
        adapterDate.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // 应用 adapter
        dateSpinner.setPrompt("选择日期");
        dateSpinner.setAdapter(adapterDate);

        dateSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String oldDate = date[0];
                date[0] = dates[position];
                if (!oldDate.equals(dates[position])) {
                    refreshTimeSpinner();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                System.out.println("Null Date");
            }
        });

        //预约时间选则
        Spinner timeSpinner = view.findViewById(R.id.time_spinner);
        times = getTimesForSpinner();

        ArrayAdapter<String> adapterTime = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, times);

        adapterTime.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        timeSpinner.setPrompt("选择时间");
        timeSpinner.setAdapter(adapterTime);

        timeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                time[0] = times[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                System.out.println("Null Time");
            }
        });

        //预约按钮
        Button buttonBook = view.findViewById(R.id.button_book);
        buttonBook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences1 = requireActivity().getSharedPreferences("localData", 0);

                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("doctorId", docId);
                    int patientId = sharedPreferences1.getInt("patientId", -1);
                    jsonObject.put("patientId", Integer.toString(patientId));
                    String appointmentTime = date[0] + " " + time[0] + ":00";
                    jsonObject.put("appointmentTime", appointmentTime);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());

                Request request = new Request.Builder()
                        .url(urlData.doOrder())
                        .post(requestBody)
                        .build();

                OkHttpClient client = new OkHttpClient();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        // 请求失败
                        requireActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(requireContext(), "网络问题", Toast.LENGTH_SHORT).show();
                            }
                        });
                        e.printStackTrace(); // 打印异常堆栈跟踪，以获取更多信息
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        if (response.isSuccessful()){
                            final String responseData = response.body().string();

                            try {
                                JSONObject jsonObject = new JSONObject(responseData);
                                int code = jsonObject.getInt("code");

                                if (code == 666) {
                                    requireActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(requireContext(), "预约成功", Toast.LENGTH_SHORT).show();
                                            NotificationsFragment notificationsFragment = new NotificationsFragment();
                                            NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment_activity_main);
                                            navController.navigate(R.id.navigation_notifications);
                                        }
                                    });
                                } else if (code == 701) {
                                    requireActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(requireContext(), "该医生已达最大人数", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                } else{
                                    requireActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            System.out.println(jsonObject.toString());
                                            Toast.makeText(requireContext(), "预约失败", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                requireActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(requireContext(), "解析错误", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    }
                });
            }
        });

        return view;
    }

    private void refreshTimeSpinner(){
        Spinner timeSpinner = getView().findViewById(R.id.time_spinner);
        times = getTimesForSpinner(); // 使用当前选择的日期重新获取时间选项

        ArrayAdapter<String> adapterTime = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, times);
        adapterTime.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        timeSpinner.setAdapter(adapterTime);
    }

    private String[] getDatesForSpinner() {
        Calendar calendar = Calendar.getInstance();
        List<String> dates = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Integer hour = calendar.get(Calendar.HOUR_OF_DAY);
        Integer minute = calendar.get(Calendar.MINUTE);
        if ((hour > 17) || (hour == 17  && minute > 30)) {
            calendar.add(Calendar.DATE, 1);
        }


        Date date = calendar.getTime();
        this.date[0] = dateFormat.format(date);

        for (int i = 0; i < 3; i++) {
            // 设置日期格式为 YYYY-MM-DD
            date = calendar.getTime();
            dates.add(dateFormat.format(date));

            // 为第二天准备
            calendar.add(Calendar.DATE, 1);
        }

        return dates.toArray(new String[0]);
    }

    private String[] getTimesForSpinner() {
        Calendar calendar = Calendar.getInstance();
        List<String> times = new ArrayList<>();
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
        SimpleDateFormat dateTimeSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date curDateTime = new Date();

        calendar.set(Calendar.HOUR_OF_DAY, 9);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        while(!(calendar.get(Calendar.HOUR_OF_DAY) == 18)){
            Date date = calendar.getTime();
            String dateTime = this.date[0] + " " + timeFormat.format(date);
            try {
                Date newTime = dateTimeSDF.parse(dateTime);
                if(!newTime.before(curDateTime) && !(isOffWork(calendar))) times.add(timeFormat.format(date));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            if(calendar.get(Calendar.MINUTE) == 0){
                calendar.set(Calendar.MINUTE, 30);
            } else {
                calendar.add(Calendar.HOUR_OF_DAY, 1);
                calendar.set(Calendar.MINUTE, 0);
            }
        }

        return times.toArray(new String[0]);
    }

    private Boolean isOffWork(Calendar calendar){
        Integer hour = calendar.get(Calendar.HOUR_OF_DAY);
        Integer minute = calendar.get(Calendar.MINUTE);

        boolean tooEarly = (hour < 9);
        boolean noon = (hour == 12 || hour == 13);
        boolean tooLate = (hour > 17) || (hour == 17  && minute > 30);

        return tooEarly || noon || tooLate;
    }
}